package com.platform.usercenter.controller;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.platform.common.core.constant.ServiceNameConstants;
import com.platform.common.core.domain.R;
import com.platform.common.core.domain.entity.SysUser;
import com.platform.common.core.domain.model.LoginUser;

import com.platform.constants.SysUserConstants;
import com.platform.file.api.remote.api.RemoteFileService;
import com.platform.file.api.remote.vo.SysFile;
import com.platform.file.api.remote.vo.SysFileDto;
import com.platform.usercenter.domain.SysUserDept;
import com.platform.usercenter.domain.query.SysUserDeptQuery;
import com.platform.usercenter.service.ISysUserDeptService;
import com.platform.usercenter.service.ImService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.platform.common.core.utils.StringUtils;
import com.platform.common.core.utils.file.FileTypeUtils;
import com.platform.common.core.utils.file.MimeTypeUtils;
import com.platform.common.core.web.controller.BaseController;
import com.platform.common.core.web.domain.AjaxResult;
import com.platform.common.security.service.TokenService;
import com.platform.common.security.utils.SecurityUtils;
import com.platform.usercenter.service.ISysUserService;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * 个人信息 业务处理
 *
 * @author
 */
@RestController
@RequestMapping("/user/profile")
public class SysProfileController extends BaseController
{
    @Resource
    private ISysUserService userService;

    @Resource
    private TokenService tokenService;

    @Resource
    private RemoteFileService remoteFileService;

    @Resource
    private ISysUserDeptService sysUserDeptService;

    @Resource
    ImService imService;

    /**
     * 个人信息
     */
    @GetMapping
    public AjaxResult profile()
    {
        String username = SecurityUtils.getUsername();
        SysUser user = userService.selectUserByUserName(username);
        /**
         * 获取当前登入用户部门信息
         */
        SysUserDeptQuery sysUserDept=new SysUserDeptQuery();
        sysUserDept.setUserId(user.getUserId());
        sysUserDept.setDeptId(user.getDeptId());//当前用户登入部门
        List<SysUserDept> sysUserDeptList = sysUserDeptService.selectSysUserDeptList(sysUserDept);

        AjaxResult ajax = AjaxResult.success(user);
        ajax.put("roleGroup", userService.selectUserRoleGroup(username));
        ajax.put("postGroup", userService.selectUserPostGroup(username));
        ajax.put("userDept", CollectionUtils.isNotEmpty(sysUserDeptList)?sysUserDeptList.get(0):new ArrayList<>());

        return ajax;
    }

    /**
     * 修改用户
     */
    @PutMapping
    public AjaxResult updateProfile(@RequestBody SysUser user)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        user.setUserName(sysUser.getUserName());
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUserId(sysUser.getUserId());
        user.setPassword(null);
        user.setAvatar(null);
        user.setDeptId(null);
        if (userService.updateUserProfile(user) > 0)
        {
            // 更新缓存用户信息
            loginUser.getSysUser().setNickName(user.getNickName());
            loginUser.getSysUser().setPhonenumber(user.getPhonenumber());
            loginUser.getSysUser().setEmail(user.getEmail());
            loginUser.getSysUser().setSex(user.getSex());
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(String oldPassword, String newPassword)
    {
        String username = SecurityUtils.getUsername();
        SysUser user = userService.selectUserByUserName(username);
        String password = user.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            return error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return error("新密码不能与旧密码相同");
        }
        boolean matches = newPassword.matches(SysUserConstants.PW_PATTERN);
        if(matches == false)
        {
              return error("密码必须是8-20位且包含大小写字母、数字、特殊字符！");
        }
        if (userService.resetUserPwd(username, SecurityUtils.encryptPassword(newPassword)) > 0)
        {
            // 更新缓存用户密码
            LoginUser loginUser = SecurityUtils.getLoginUser();
            loginUser.getSysUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            try {
                imService.updateImUserPwd(user.getUserId(),SecurityUtils.encryptPassword(newPassword));
            }catch (Exception e){
                logger.error("****更新IM用户密码异常：{}",e.getMessage());
                e.printStackTrace();
            }
            return success();
        }
        return error("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file)
    {
        if (!file.isEmpty())
        {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            String extension = FileTypeUtils.getExtension(file);
            if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION))
            {
                return error("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
            }
            R<SysFile> fileResult = remoteFileService.upload(file, ServiceNameConstants.USER_CENTER_SERVICE,ServiceNameConstants.USER_CENTER_SERVICE,"1");
            if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData()))
            {
                return error("文件服务异常，请联系管理员");
            }
            String url = fileResult.getData().getUrl();
            if (userService.updateUserAvatar(loginUser.getUsername(), url))
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", url);
                // 更新缓存用户头像
                loginUser.getSysUser().setAvatar(url);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return error("上传图片异常，请联系管理员");
    }


    /**
     * 获取 图片回显的 guid
     * @return
     * @throws Exception
     */
    @GetMapping("/getGuid")
    public R getGuid(Integer num){

        return remoteFileService.getGuid(num,ServiceNameConstants.USER_CENTER_SERVICE);
    }
    /**
     * 批量上传

     * @param files
     * @return
     */
    @PostMapping("/uploadFile")
    public R<List<String>> uploadFile(@RequestBody List<Map<String, String>> files) {

        if (files == null||files.size()==0) {
            return  R.fail("上传文件不能为空");
        }
        List<String> filenameList=new ArrayList<>();
        SysFileDto dto=new SysFileDto();
        dto.setFiles(files);
        dto.setServiceName(ServiceNameConstants.USER_CENTER_SERVICE);
        return remoteFileService.uploadFile(dto,ServiceNameConstants.USER_CENTER_SERVICE);

    }
    /**
     * 上传
     * @param
     * @param
     * @return
     */
    @PostMapping("/uploadmultipartFile")
    public R<String> uploadmultipartFile(@RequestParam("file") MultipartFile file) {
        if (file == null) {
            return  R.fail("上传文件不能为空");
        }
        return remoteFileService.uploadmultipartFile(file, ServiceNameConstants.USER_CENTER_SERVICE,ServiceNameConstants.USER_CENTER_SERVICE,"0");

    }
    /**
     * 批量上传
     * @param
     * @param files
     * @return
     */
    @PostMapping("/bathUploadFile")
    public R<List<String>> bathUploadFile(@RequestParam("files") MultipartFile[] files) {
        if (files == null) {
            return  R.fail("上传文件不能为空");
        }
        List<String> filenameList=new ArrayList<>();
        for (int i=0;i<files.length;i++){
            String filename;
            R<String> stringR=remoteFileService.uploadmultipartFile(files[i], ServiceNameConstants.USER_CENTER_SERVICE,ServiceNameConstants.USER_CENTER_SERVICE,"0");
            filename=stringR.getData();
            filenameList.add(filename);
        }
        return R.ok(filenameList);


    }
    /**
     * 查看图片服务接口
     */
    @GetMapping("/previewFile")
    public void previewFile(@RequestParam("fileName") String fileName, String guid, HttpServletResponse response){
        try {
            feign.Response entity= remoteFileService.getInputStream(fileName,guid,ServiceNameConstants.USER_CENTER_SERVICE);
//
            InputStream fileStream= entity.body().asInputStream();
            if(fileStream!=null){
                //如果需要下载文件，去掉下面的注释
//                response.setHeader("content-disposition", "attachment;");
                ServletOutputStream outputStream = response.getOutputStream();
                int len = 0;
                byte[] data = new byte[1024];
                while ((len = fileStream.read(data)) != -1) {
                    outputStream.write(data, 0, len);
                }
                outputStream.close();
                fileStream.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * xiazai图片服务接口
     */
    @GetMapping("/downLoadFile")
    public void downLoadFile(@RequestParam("fileName") String fileName, String guid, HttpServletResponse response){
        try {
            feign.Response entity= remoteFileService.getInputStream(fileName,guid,ServiceNameConstants.USER_CENTER_SERVICE);
//
            InputStream fileStream= entity.body().asInputStream();
            if(fileStream!=null){
                //如果需要下载文件，去掉下面的注释
                response.setHeader("content-disposition", "attachment;");
                ServletOutputStream outputStream = response.getOutputStream();
                int len = 0;
                byte[] data = new byte[1024];
                while ((len = fileStream.read(data)) != -1) {
                    outputStream.write(data, 0, len);
                }
                outputStream.close();
                fileStream.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * 删除文件
     * @param
     * @param
     * @return
     */
    @GetMapping("/deleteFile")
    public R deleteFile(@RequestParam("fileName")String fileName) {

        if (fileName == null||fileName=="") {
            return  R.fail("删除文件路径不能为空");
        }
        return remoteFileService.deleteFile(fileName,ServiceNameConstants.USER_CENTER_SERVICE);

    }


}
